<template>
  <div class="mod-dytz">
    <el-form :inline="true" :model="searchForm" @keyup.enter.native="initPage()">
      <el-form-item>
        <el-input v-model="searchForm.wtdh" maxlength="30" placeholder="问题单号" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="searchForm.yffzrYf" maxlength="30" placeholder="乙方负责人" clearable filterable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="searchForm.wtbt" maxlength="30" placeholder="问题标题" clearable filterable></el-input>
      </el-form-item>
      <el-form-item>
        <el-dict code="DYCS_LIST" v-model="searchForm.dycsYf" placeholder="对应厂商" clearable filterable></el-dict>
      </el-form-item>
      <el-form-item>
        <el-dict code="YYXT_LIST" v-model="searchForm.yyxtJf" placeholder="应用系统" clearable filterable></el-dict>
      </el-form-item>
      <el-form-item>
        <el-dict code="XTZT_LIST" v-model="searchForm.wtztYf" placeholder="问题专题" clearable filterable></el-dict>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchForm.isSelfCreate"
                   placeholder="查询范围"
                   filterable
                   class="width100"
                   size="small">
          <el-option
            :key="true"
            label="只查自己新建问题"
            :value="true">
          </el-option>
          <el-option
            :key="false"
            label="查询全部"
            :value="false">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          @change="searchJdsjJfChange"
          end-placeholder="接单结束时间"
          range-separator="至"
          start-placeholder="接单开始时间"
          style="width: 100%"
          type="datetimerange"
          v-model="searchJdsjJf"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          @change="jjrqYfsearchTimeChange"
          end-placeholder="解决结束时间"
          range-separator="至"
          start-placeholder="解决开始时间"
          style="width: 100%"
          type="datetimerange"
          v-model="jjrqYfsearchTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-dict code="DYZTJF_LIST" v-model="searchForm.dyztJf" placeholder="问题状态" clearable filterable></el-dict>
      </el-form-item>
      <el-form-item>
        <el-dict code="WTLXYF_LIST" v-model="searchForm.wtlxYf" placeholder="问题类型" clearable filterable></el-dict>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchForm.isZdwt"
                   placeholder="是否重大"
                   clearable
                   class="width100"
                   size="small">
          <el-option
            :key="true"
            label="是"
            :value="1">
          </el-option>
          <el-option
            :key="false"
            label="否"
            :value="0">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchForm.isMqzt"
                   placeholder="是否确定的专题"
                   clearable
                   class="width100"
                   size="small">
          <el-option
            :key="true"
            label="是"
            :value="1">
          </el-option>
          <el-option
            :key="false"
            label="否"
            :value="0">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchForm.isZbnr"
                   placeholder="是否计入周报"
                   clearable
                   class="width100"
                   size="small">
          <el-option
            :key="true"
            label="是"
            :value="1">
          </el-option>
          <el-option
            :key="false"
            label="否"
            :value="0">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="initPage()">查询</el-button>
        <el-button v-if="isAuth('zr:dytz:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
        <el-button v-if="isAuth('zr:dytz:delete')" type="danger" @click="deleteHandle()"
                   :disabled="dataListSelections.length <= 0">批量删除
        </el-button>
        <el-button v-if="isAuth('zr:dytz:save')" type="warning" icon="el-icon-download" @click="importHandel()">
          导入
        </el-button>
        <el-button v-if="isAuth('zr:dytz:export')" type="info" @click="exportExcel()">导出</el-button>
        <el-button v-if="isAuth('zr:dytz:update')" type="success" @click="batchedit()"
                   :disabled="dataListSelections.length <= 0">批量修改
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="wtdh"
        header-align="center"
        :show-overflow-tooltip="true"
        align="center"
        label="问题单号">
      </el-table-column>
      <el-table-column
        prop="wtbt"
        header-align="center"
        :show-overflow-tooltip="true"
        align="center"
        label="问题标题">
      </el-table-column>
      <el-table-column
        prop="wtztYf"
        header-align="center"
        :show-overflow-tooltip="true"
        align="center"
        label="问题专题">
      </el-table-column>
      <el-table-column
        prop="wtly"
        header-align="center"
        :show-overflow-tooltip="true"
        align="center"
        label="问题来源">
      </el-table-column>
      <el-table-column
        prop="wtlxYfmc"
        header-align="center"
        :show-overflow-tooltip="true"
        align="center"
        label="问题类型-乙方">
      </el-table-column>
      <el-table-column
        prop="jdsjJf"
        header-align="center"
        :show-overflow-tooltip="true"
        :formatter="formatDate"
        align="center"
        label="接单时间">
      </el-table-column>
      <el-table-column
        prop="jjrqYf"
        header-align="center"
        :show-overflow-tooltip="true"
        :formatter="formatDate"
        align="center"
        label="解决时间(乙方)">
      </el-table-column>
      <el-table-column
        prop="createTime"
        header-align="center"
        :show-overflow-tooltip="true"
        align="center"
        label="录入日期">
      </el-table-column>
      <el-table-column
        prop="yffzrYf"
        header-align="center"
        :show-overflow-tooltip="true"
        align="center"
        label="乙方负责人">
      </el-table-column>
      <el-table-column
        prop="isZdwt"
        header-align="center"
        :show-overflow-tooltip="true"
        align="center"
        label="重大问题">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isZdwt === true" size="small" type="danger">是</el-tag>
          <el-tag v-else-if="scope.row.isZdwt === false" size="small" type="success">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="isZbnr"
        header-align="center"
        :show-overflow-tooltip="true"
        align="center"
        label="计入周报">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isZbnr === true" size="small" type="danger">是</el-tag>
          <el-tag v-else-if="scope.row.isZbnr === false" size="small" type="success">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="dyztJf"
        header-align="center"
        :show-overflow-tooltip="true"
        align="center"
        label="问题状态">
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button v-if="isAuth('zr:dytz:info')" type="text" size="small" @click="showDetails(scope.row.wtdh)">查看
          </el-button>
          <el-dropdown trigger="click">
              <span class="el-dropdown-link" style="cursor: pointer;">
                更多<i class="el-icon-arrow-down el-icon-right"/>
              </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="isAuth('zr:dytz:update')" @click.native="addOrUpdateHandle(scope.row.wtdh)">修改
              </el-dropdown-item>
              <el-dropdown-item v-if="isAuth('zr:dytz:delete')" @click.native="deleteHandle(scope.row.wtdh)">删除
              </el-dropdown-item>
              <el-dropdown-item v-if="isAuth('zr:dytz:converZentao')" @click.native="converZentao(scope.row.wtdh)">转禅道
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <edit-zentao-bug v-if="zentaoVisible" ref="zentaoRef"></edit-zentao-bug>
    <batch-edit v-if="batchEditVisible" ref="batchEditRef"  @refreshDataList="getDataList"></batch-edit>
    <!-- 导入 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-form :model="upload.data">
        <el-row>
          <el-col :span="12">
            <el-form-item>
              <el-select v-model="upload.data.drbz" placeholder="导入内容">
                <el-option key="ZXZZDYD" label="多云工单(自行组装)" value="ZXZZDYD"></el-option>
                <el-option key="FDYGD" label="非多云工单(体外问题)" value="FDYGD"></el-option>
                <el-option key="DYSJD" label="多云平台(事件单)" value="DYSJD"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item>
              <el-upload
                ref="upload"
                :limit="1"
                accept=".xlsx, .xls"
                :headers="upload.headers"
                :action="upload.url"
                :disabled="upload.isUploading"
                :before-upload="beforeUpload"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                :data="upload.data"
                drag
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或
                  <em>点击上传</em>
                </div>
                <div class="el-upload__tip" slot="tip">
                  <a id="linkUrl" class="btn-download" style="font-size:12px;cursor: pointer"
                     @click="downloadTemplate('zr_dytz_all_import.xlsx')">
                    <i class="icon-download"></i>[全量字段模板]</a>
                  <a id="linkUrl1" class="btn-download" style="font-size:12px;cursor: pointer"
                     @click="downloadTemplate('zr_dytz_dysjd_import.xlsx')">
                    <i class="icon-download"></i>[多云事件单模板]</a>
                  <a id="linkUrl2" class="btn-download" style="font-size:12px;cursor: pointer"
                     @click="downloadTemplate('zr_dytz_yf_import.xlsx')">
                    <i class="icon-download"></i>[乙方导入模板]</a>
                  <a id="linkUrl3" class="btn-download" style="font-size:12px;cursor: pointer"
                     @click="downloadTemplate('zr_dytz_yj_fdy_import.xlsx')">
                    <i class="icon-download"></i>[乙方非多云模板]</a>
                </div>
                <div
                  class="el-upload__tip"
                  style="color:red"
                  slot="tip"
                > 1、仅允许导入“xls”或“xlsx”格式文件！<br/>
                  2、批量导入为增量导入，不会覆盖原有数据，请谨慎操作;<br/>
                  3、建议“下载模板”，在下载的Excle文件中根据批注要求录入数据;<br/>
                  4、增量导入会将所有Excle数据写入系统;
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import AddOrUpdate from './dytz-add-or-update'
import editZentaoBug from '../zt/editZentaoBug'
import batchEdit from './batch-edit'

export default {
  data() {
    return {
      searchJdsjJf: [],
      jjrqYfsearchTime: [],
      searchForm: {
        wtdh: '',
        yffzrYf: '',
        dycsYf: '',
        yyxtJf: '',
        jdsjJfq: '',
        jdsjJfz: '',
        jjrqYfq: '',
        jjrqYfz: '',
        wtztYf: '',
        wtbt: '',
        isSelfCreate: true,
        dyztJf: '',
        wtlxYf: '',
        isZdwt: '',
        isMqzt: '',
        isZbnr: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListSelections: [],
      addOrUpdateVisible: false,
      batchEditVisible: false,
      zentaoVisible: false,
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        data: {
          drbz: 'ZXZZDYD'
        },
        // 设置上传的请求头部
        headers: {
          enctype: 'multipart/form-data',
          cityCode: ''
        },
        // 上传的地址
        url: this.$http.BASE_URL + `/zr/dytz/importExcle?token=${this.$cookie.get('token')}`
      }
    }
  },
  components: {
    AddOrUpdate,
    editZentaoBug,
    batchEdit
  },
  activated() {
    this.searchForm.yffzrYf = this.$store.state.user.realName
    this.getDataList()
  },
  methods: {
    // 页面初始化
    initPage() {
      this.pageIndex = 1
      this.getDataList()
    },
    // 获取数据列表
    getDataList() {
      this.$http({
        url: '/zr/dytz/list',
        method: 'get',
        params: {
          'page': this.pageIndex,
          'limit': this.pageSize,
          'wtdh': this.searchForm.wtdh,
          'yffzrYf': this.searchForm.yffzrYf,
          'dycsYf': this.searchForm.dycsYf,
          'yyxtJf': this.searchForm.yyxtJf,
          'jdsjJfq': this.searchForm.jdsjJfq,
          'jdsjJfz': this.searchForm.jdsjJfz,
          'jjrqYfq': this.searchForm.jjrqYfq,
          'jjrqYfz': this.searchForm.jjrqYfz,
          'wtztYf': this.searchForm.wtztYf,
          'wtbt': this.searchForm.wtbt,
          'isSelfCreate': this.searchForm.isSelfCreate,
          'dyztJf': this.searchForm.dyztJf,
          'wtlxYf': this.searchForm.wtlxYf,
          'isZdwt': this.searchForm.isZdwt,
          'isMqzt': this.searchForm.isMqzt,
          'isZbnr': this.searchForm.isZbnr
        }
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.page.records
          this.totalPage = data.page.total
        } else {
          this.dataList = []
          this.totalPage = 0
        }
      })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 查看详情
    showDetails(wtdh) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(wtdh, true)
      })
    },
    // 新增 / 修改
    addOrUpdateHandle(wtdh) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(wtdh, false)
      })
    },
    batchedit() {
      let ids = this.dataListSelections.map(item => {
        return item.wtdh
      })
      this.batchEditVisible = true
      this.$nextTick(() => {
        this.$refs.batchEditRef.init(ids)
      })
    },
    // 删除
    deleteHandle(wtdh) {
      let ids = wtdh ? [wtdh] : this.dataListSelections.map(item => {
        return item.wtdh
      })
      this.$confirm(`确定对[id=${ids.join(',')}]进行[删除]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: '/zr/dytz/delete',
          method: 'post',
          data: ids
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500
            })
            this.getDataList()
          }
        })
      }).catch(() => {
      })
    },
    /**
     * 转禅道
     * @param wtdh
     */
    converZentao(wtdh) {
      this.zentaoVisible = true
      this.$nextTick(() => {
        this.$refs.zentaoRef.initDyWtdh(wtdh, true)
      })
    },
    // 接单时间时间范围
    searchJdsjJfChange(val) {
      if (!val) {
        this.searchForm.jdsjJfq = ''
        this.searchForm.jdsjJfz = ''
        return
      }
      this.searchForm.jdsjJfq = val[0]
      this.searchForm.jdsjJfz = val[1]
    },
    // 关单时间时间范围
    jjrqYfsearchTimeChange(val) {
      if (!val) {
        this.searchForm.jjrqYfq = ''
        this.searchForm.jjrqYfz = ''
        return
      }
      this.searchForm.jjrqYfq = val[0]
      this.searchForm.jjrqYfz = val[1]
    },
    /**
     * 导出公共服务-其他
     */
    exportExcel() {
      this.$http({
        url: '/zr/dytz/exportList',
        method: 'post',
        responseType: 'blob',
        params: this.searchForm
      }).then(({data}) => {
        if (!data || data.size === 0) {
          this.$message({
            message: '列表为空',
            type: 'error',
            duration: 1500
          })
          return
        }
        let blob = new Blob([data], {type: 'application/vnd.ms-excel'})
        let url = window.URL.createObjectURL(blob)
        const link = document.createElement('a') // 创建a标签
        link.href = url
        link.download = '多云问题台账.xls' // 重命名文件
        link.click()
        URL.revokeObjectURL(url) // 释放内存
      })
    },
    // wmqztExportExcel() {
    //   let searchFormData = JSON.parse(JSON.stringify(this.searchForm))
    //   searchFormData['isMqzt'] = '1'
    //   this.$http({
    //     url: '/zr/dytz/exportList',
    //     method: 'post',
    //     responseType: 'blob',
    //     params: searchFormData
    //   }).then(({data}) => {
    //     if (!data || data.size === 0) {
    //       this.$message({
    //         message: '列表为空',
    //         type: 'error',
    //         duration: 1500
    //       })
    //       return
    //     }
    //     let blob = new Blob([data], {type: 'application/vnd.ms-excel'})
    //     let url = window.URL.createObjectURL(blob)
    //     const link = document.createElement('a') // 创建a标签
    //     link.href = url
    //     link.download = '未明确主题多云问题列表.xls' // 重命名文件
    //     link.click()
    //     URL.revokeObjectURL(url) // 释放内存
    //   })
    // },
    /**
     * 导入
     */
    importHandel() {
      this.upload.data.isDygd = true
      this.upload.open = true
    },
    beforeUpload(file) {
      // 上传前配置
      let excelfileExtend = '.xls,.xlsx'// 设置文件格式
      let fileExtend = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      if (excelfileExtend.indexOf(fileExtend) <= -1) {
        this.$message.error('文件格式错误')
        return false
      }
    },
// 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
// 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      if (response && response.code === 0) {
        this.$alert('已经导入数据数量：' + response.size + (response.errorMsg ? ',发生如下错误：</br>' + response.errorMsg : response.importNo ? ';导入流水号：' + response.importNo : ''),
          '导入结果',
          {dangerouslyUseHTMLString: true})
        this.getDataList()
      } else {
        this.$message.error(response.msg)
      }
    },
    submitFileForm() {
      this.$refs.upload.submit()
    },
    downloadTemplate(fileName) {
      this.$http({
        url: '/sys/oss/downloadTemplate',
        method: 'get',
        params: {
          fileName: fileName
        },
        responseType: 'blob'
      }).then(({data}) => {
        if (!data || data.size === 0) {
          this.$message({
            message: '下载失败',
            type: 'error',
            duration: 1500
          })
          return
        }
        let url = window.URL.createObjectURL(new Blob([data]))
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', `运维问题导入模板.xlsx`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      }).catch(() => {
      })
    },
    // 方法区
    formatDate(row, column) {
      // 获取单元格数据
      let data = row[column.property]
      if (data == null) {
        return null
      }
      let dt = new Date(data)
      return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()
    },
    // 本周周报导出
    exportWeekBook() {
      this.$confirm(`确定对进行[本周周报]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: '/zr/dytz/dowloadWeekBook',
          method: 'get',
          responseType: 'blob'
        }).then(({data}) => {
          if (!data || data.size === 0) {
            this.$message({
              message: '下载失败',
              type: 'error',
              duration: 1500
            })
            return
          }
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', data.filename)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(url)
        }).catch(() => {
        })
      })
    }
  }
}
</script>
